package com.future.myjavatools.core.zhoupu;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author gavincoder
 * @remark http请求类封装
 */
@Slf4j
public class RequestUtil {
    
    /**
     * 前端无请求默认为-1
     */
    public final static int NO_REQUEST = -1;


    public static String readRequestBody(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
           log.error("read request stream exception",e);
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将请求中的参数序列化成字符串
     *
     * @param request
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String convertParametersAsString(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        Enumeration<String> paramEnum = request.getParameterNames();
        boolean isAppend = false;
        while (paramEnum.hasMoreElements()) {
            String paramName = paramEnum.nextElement();
            if (isAppend) {
                sb.append("&");
            }
            sb.append(paramName + "=" + request.getParameter(paramName));
            isAppend = true;
        }
        return sb.toString();
    }

    public static Map<String, String> getParameterMapIgnoreCase(HttpServletRequest request) {
        Map<String, String> resultMap = Maps.newHashMap();
        if (request.getParameterNames() == null) {
            return resultMap;
        }

        Enumeration<String> paramEnum = request.getParameterNames();
        while (paramEnum.hasMoreElements()) {
            String paramName = paramEnum.nextElement();
            resultMap.put(paramName.toLowerCase(), request.getParameter(paramName));
        }
        return resultMap;
    }

    public static int getIntParameter(HttpServletRequest request, String paramKey) {
        String value = request.getParameter(paramKey);
        if (value == null) {
            return 0;
        } else {
            return Integer.parseInt(value);
        }
    }


    /**
     * 获取相对的请求完整路径字符串:如:/room/list.htm?a=b&c=d
     *
     * @param request
     * @return
     */
    public static String getRelativeReqUrl(HttpServletRequest request) {
        return request.getServletPath() + "?" + convertParametersAsString(request);
    }


    /**
     * 功能描述：<br>
     * 请求是否ajax请求
     *
     * @param request
     * @return true是ajax请求 false非ajax请求
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        return StringUtils.equalsIgnoreCase(request.getHeader("x-requested-with"), "XMLHttpRequest");
    }

    /**
     * 功能描述：<br>
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public static String getUserIp(HttpServletRequest request) {
        String ip = request.getHeader("x-real-ip");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        int pos = ip.indexOf(',');
        if (pos >= 0) {
            ip = ip.substring(0, pos);
        }
        return ip;
    }
}
